<template>
  <div class="search_page">
    <!-- 顶部导航栏 -->
    <NavBar title="搜索">
      <template #left>
        <RouterLink :to="{ name: 'home' }">
          <Icon name="zuojiantou" color="#fff" size="20" />
        </RouterLink>
      </template>
    </NavBar>
    <div class="comment_list_wrap_search">
      <div class="input_wrap">
        <div class="lf">
          <Icon name="search1" color="#a6a5a4" size="21"></Icon>
        </div>
        <input :placeholder="Inputplaceholder" class="input" ref="InputRef" v-model="InputVal" @input="handleInput">
        <div class="rt" v-if="isShow">
          <Icon name="close" color="#a6a5a4" size="12"></Icon>
        </div>
      </div>
    </div>
    <!-- 搜索结果选项卡 -->
    <Tab v-model="currentIndex" @Tabchange="handleTabChange" class="flex-grow">
      <TabItem label="视频">
        <!-- 正在加载 -->
        <div v-if="videoLoading" class="no_data">搜索中...</div>
        <div class="search_user_video_list" v-if="searchResults.length">
          <div v-for="item in searchResults" :key="item.id" class="item" @click="handleVideoClick(item)">
            <div class="avatar">
              <img :src="item.Video.videoCover" alt="" />
            </div>
            <div class="item_bottom_info">
              <div class="item_bottom_info_desc">{{ item.Video.videoDesc }}</div>
              <div class="item_bottom_info_user">
                <div class="item_bottom_info_user_userimg">
                  <img :src="item.Video.userAvatar" alt="">
                  <span class="item_bottom_info_user_userimg_name">{{ item.Video.userNickname }}</span>
                </div>
                <div class="item_bottom_info_user_lick">
                  <div class="item_bottom_info_user_lick_item">
                    <Icon name="xin-2" size="14" color="#fff"></Icon>
                    <span class="item_bottom_info_user_lick_num">{{ item.WSLCNum.likeNum }}</span>
                  </div>
                  <div class="item_bottom_info_user_lick_item">
                    <Icon name="pinglun" size="14" color="#fff"></Icon>
                    <span class="item_bottom_info_user_lick_num">{{ item.WSLCNum.commentNum }}</span>
                  </div>
                  <div class="item_bottom_info_user_lick_item">
                    <Icon name="a-fenxiangweifenxiang" size="13" color="#fff"></Icon>
                    <span class="item_bottom_info_user_lick_num">{{ item.WSLCNum.commentNum }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-else-if="isVideoEmpty" class="no_data">
          您搜索的关键词暂无视频，请更换关键词~
        </div>
        <!-- 未搜索（默认引导） -->
        <div v-else-if="showVideoPlaceholder" class="no_data">
          请搜索自己喜欢的视频
        </div>
      </TabItem>
      <TabItem label="用户">
        <!-- 正在加载 -->
        <div v-if="userLoading" class="no_data">搜索中...</div>
        <div class="fan_list" v-if="searchUserResults.length">
          <div class="fan_item" v-for="item in searchUserResults" :key="item.userId"
            @click="handleUserClick(item.userId)">
            <div class="avatar">
              <img :src="item.userAvatar" alt="">
            </div>
            <div class="info">
              <div class="name">
                {{ item.userNickname }}
              </div>
              <div class="desc">
                {{ item.userDesc }}
              </div>
            </div>
            <div class="follow" :class="{ 'active': item.myRelation !== 'none' }" @click="handleFollow(item.userId)">
              {{ item.myRelation !== 'none' ? '已关注' : '关注' }}
            </div>
          </div>
        </div>
        <!-- 已搜索但无结果 -->
        <div v-else-if="isUserEmpty" class="no_data">
          您搜索的关键词暂无用户，请更换关键词~
        </div>

        <!-- 默认显示暂无数据快搜索吧~ -->
        <!-- 未搜索（默认引导） -->
        <div v-else-if="showUserPlaceholder" class="no_data">
          搜索要关注的人的 ID
        </div>
      </TabItem>
    </Tab>
    <!-- 从左到右过渡出现 视频播放页 -->
    <transition name="fade-in-right">
      <VideoPlaybackPage v-if="isShowVideoPlaybackPage" v-model="isShowVideoPlaybackPage" :data="videoPlaybackData">
      </VideoPlaybackPage>
    </transition>

  </div>
</template>
<script setup>

import { ref, computed, onBeforeUnmount } from 'vue'
import Icon from '@/components/Common/Icon/index.vue'
import NavBar from '@/components/Common/NavBar/index.vue'
import Tab from '@/components/Common/Tabs/index.vue'
import TabItem from '@/components/Common/TabItem/index.vue'
import { searchAPI, searchUserIdAPI, followAPI } from '@/api/Home'
import { useUserIDStore } from '@/stores/UserID'

const userIDStore = useUserIDStore()
const userId = userIDStore.userInfo?.userId

const InputVal = ref('')
const currentIndex = ref(0)
const searchResults = ref([])
const searchUserResults = ref([])
const hasSearched = ref(false) // 新增：是否已触发搜索

// 是否显示“暂无”提示（已搜索但无结果）
const isVideoEmpty = computed(() => {
  return hasSearched.value && currentIndex.value === 0 && searchResults.value.length === 0
})
const isUserEmpty = computed(() => {
  return hasSearched.value && currentIndex.value === 1 && searchUserResults.value.length === 0
})

// 是否显示默认引导语（未搜索）
const showVideoPlaceholder = computed(() => {
  return !hasSearched.value && currentIndex.value === 0
})
const showUserPlaceholder = computed(() => {
  return !hasSearched.value && currentIndex.value === 1
})

const isShow = computed(() => InputVal.value !== '')
const Inputplaceholder = computed(() => {
  return currentIndex.value === 0
    ? '输入关键词进行搜索(视频)'
    : '输入关键词进行搜索(用户昵称)'
})

const handleTabChange = (index) => {
  InputVal.value = ''
  currentIndex.value = index
  hasSearched.value = false // 切换 tab 时重置搜索状态
  searchResults.value = []
  searchUserResults.value = []
}

// 防抖（可选但推荐）
let searchTimeout = null
let currentAbortController = null // 用于取消上一次请求（可选）

const handleInput = () => {
  // 清除上一次防抖
  if (searchTimeout) clearTimeout(searchTimeout)

  // 如果输入为空，重置状态
  if (InputVal.value.trim() === '') {
    hasSearched.value = false
    searchResults.value = []
    searchUserResults.value = []
    videoLoading.value = false
    userLoading.value = false
    return
  }

  // 取消上一次请求（如果你的 API 支持 signal）
  if (currentAbortController) {
    currentAbortController.abort()
  }

  searchTimeout = setTimeout(async () => {
    hasSearched.value = true

    // 根据当前 Tab 设置 loading
    if (currentIndex.value === 0) {
      videoLoading.value = true
      userLoading.value = false
    } else {
      userLoading.value = true
      videoLoading.value = false
    }

    try {
      currentAbortController = new AbortController()

      if (currentIndex.value === 0) {
        const res = await searchAPI(userId, { key: InputVal.value.trim() }, {
          signal: currentAbortController.signal // 如果你的 API 使用 fetch，可传入；否则删掉这行
        })
        if (res.code === 200) {
          searchResults.value = res.data || []
          videoPlaybackData.value = res.data || []
        }
      } else {
        const res = await searchUserIdAPI(userId, { key: InputVal.value.trim() }, {
          signal: currentAbortController.signal
        })
        if (res.code === 200) {
          const data = res.data || []
          data.forEach(item => {
            if (item.userAvatar && !item.userAvatar.includes('http')) {
              item.userAvatar = 'http://43.138.15.137:3000' + item.userAvatar
            }
          })
          searchUserResults.value = data
        }
      }
    } catch (error) {
      if (error.name !== 'AbortError') {
        console.error('搜索请求失败:', error)
        // 可选：弹出错误提示
      }
    } finally {
      // 无论成功失败，关闭 loading
      videoLoading.value = false
      userLoading.value = false
    }
  }, 300)
}

// 组件卸载时清理定时器
onBeforeUnmount(() => {
  if (searchTimeout) clearTimeout(searchTimeout)
})


// loading
const videoLoading = ref(false)
const userLoading = ref(false)



// 关注/取消关注
const handleFollow = async (followUserId) => {
  try {
    const res = await followAPI(userId, followUserId)
    if (res.code === 200) {
      // 关注成功后，更新用户数据
      const userItem = searchUserResults.value.find(u => u.userId === followUserId)
      if (userItem) {
        userItem.myRelation = userItem.myRelation === 'none' ? 'follow' : 'none'
        console.log(userItem.myRelation)
      }
    }



  } catch (error) {
    console.error('关注/取消关注请求失败:', error)
  }
}


// 加载 视频播放页
import { defineAsyncComponent } from 'vue'
// 视频播放页数据
// 视频播放页数据：改为对象
const videoPlaybackData = ref({
  list: [],
  initialIndex: 0
})

const isShowVideoPlaybackPage = ref(false)
const VideoPlaybackPage = defineAsyncComponent(() => import('@/views/home/VideoPlaybackPage/index.vue'))

// 点击视频
const handleVideoClick = (item) => {
  // 找到当前点击项在 searchResults 中的索引
  const index = searchResults.value.findIndex(v => v.Video?.videoId === item.Video?.videoId)
  if (index === -1) return
  console.log(index)

  // 传递整个列表 + 初始索引
  videoPlaybackData.value = {
    list: searchResults.value,
    initialIndex: index
  }
  isShowVideoPlaybackPage.value = true
}


// 显示用户详情页
import { useRouter } from 'vue-router'
const router = useRouter()
const handleUserClick = (friendId) => {
  router.push({
    name: 'UserDetails',
    params: { friendId },
    query: { from: 'search' } // 添加来源标识
  })
}

</script>
<style lang="scss" scoped>
.search_page {
  background-color: #1a1b20;
  min-height: 100vh;
  display: flex;
  flex-direction: column;

  .flex-grow {
    flex: 1;
    display: flex;
    flex-direction: column;
  }

  .search_user_video_list {
    padding: 10px 2px;
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    flex: 1;
    align-content: flex-start;

    .item {
      width: 50%;
      height: 245px;
      margin-bottom: 5px;
      background: #1a1b20;
      overflow: hidden;
      display: flex;
      position: relative;

      .avatar {
        flex-shrink: 0;
        width: 100%;
        height: 100%;
        text-align: center;

        img {
          width: 100%;
          height: 100%;
        }
      }


      .item_bottom_info {
        position: absolute;
        left: 0;
        bottom: 0;
        padding: 8px;
        color: #e8e8e9;
        font-size: 14px;

        .item_bottom_info_desc {
          font-size: 10px;
          font-weight: bold;
          margin-bottom: 4px;
          // 最多显示三行超出...
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
        }

        .item_bottom_info_user {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .item_bottom_info_user_userimg {
            display: flex;
            align-items: center;

            img {
              width: 35px;
              height: 35px;
              border-radius: 50%;
              margin-right: 4px;
            }

            .item_bottom_info_user_userimg_name {
              font-size: 10px;
              font-weight: bold;
            }

          }

          .item_bottom_info_user_lick {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 10px;
            font-weight: bold;
          }
        }
      }


    }
  }

  // 默认显示暂无数据快搜索吧~
  .no_data {
    width: 100%;
    text-align: center;
    font-size: 14px;
    font-weight: bold;
    color: #879394;
    margin-top: 20px;
    padding-bottom: 20px;
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
  }



  .fan_list {
    padding: 10px;
    flex: 1;
    overflow-y: auto;

    .fan_item {
      display: flex;
      align-items: center;
      margin-bottom: 10px;


      .avatar {
        width: 45px;
        height: 45px;
        border-radius: 50%;
        margin-right: 10px;

        img {
          width: 100%;
          height: 100%;
          border-radius: 50%;
        }
      }

      .info {
        flex: 1;


        .name {
          font-size: 14px;
          font-weight: bold;
          line-height: 1;
          color: #fff;
        }

        .desc {
          font-size: 14px;
          color: #fff;
          margin-bottom: 5px;
          font-weight: bold;
        }

        .time {
          font-size: 12px;
          font-weight: bold;
          color: #879394;
        }
      }

      .follow {
        width: 60px;
        height: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        font-weight: bold;
        color: #fff;
        padding: 4px 8px;
        border-radius: 2px;
        white-space: nowrap;
        background-color: #f9355f;
        transition: all 0.3s ease-in-out;


        &.active {
          background-color: #393b44;

        }
      }
    }
  }






}

.comment_list_wrap_search {
  padding: 10px 20px;

  .input_wrap {
    width: 100%;
    background: #242630;
    border-radius: 5px;
    height: 44px;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    justify-content: center;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;

    .input {
      height: 21px;
      background: #1a1b20;
      -webkit-box-flex: 1;
      -ms-flex: 1;
      flex: 1;
      font-size: 14px;
      color: #e8e8e9;
      padding-left: 10px;
      background: none;
      caret-color: #face15;
    }



    .lf {
      margin-left: 10px;
    }

    .rt {
      margin-right: 10px;
    }
  }
}

// 从左到右过渡出现
.fade-in-right-enter-active,
.fade-in-right-leave-active {
  transition: all 0.3s ease-in-out;
}

.fade-in-right-enter-from,
.fade-in-right-leave-to {
  transform: translateX(100%);
  opacity: 0;
}
</style>